<template>
  <div class="page-container">
    <div class="main-layout">
      <el-container class="full-height">
        <!-- 左侧侧边栏 -->
        <el-aside width="320px" class="aside-box">
            <!-- 侧边的联系人列表
            1. 是否需要搜索功能，添加功能
            2. 联系人数据获取； -->
            <el-container  class="full-height" direction="vertical">
              <!-- 搜索栏 -->
              <el-header height="60px" class="header">
                <div class="from-search">
                    <el-input v-model="input" size="default" :prefix-icon="Search" placeholder="搜索客户" :clearable="true" />
                  </div>
              </el-header>
              <!-- 置顶栏 -->
              <header v-show="loadStatus == 3 && topItems.length > 0" class="subheader">
                  <div  v-for="item in topItems" :key="item.index_name" class="top-item" @click="clickTab(item.index_name)" @contextmenu.prevent="topItemsMenu(item, $event)">
                    <el-tooltip effect="dark" placement="top-start" :content="item.remark_name ? item.remark_name : item.name">
                      <div class="avatar">
                        <span v-show="!item.avatar">{{ (item.remark_name ? item.remark_name : item.name).substr(0, 1) }}</span>
                        <el-image v-show="item.avatar" :src="item.avatar">
                          <template #error>
                            <el-image :src="detaultAvatar" ></el-image>
                          </template>
                        </el-image>
                      </div>
                    </el-tooltip>
                    <div class="name" :class="{ active: index_name == item.index_name }">{{ item.remark_name ? item.remark_name : item.name }}</div>
                  </div>
                </header>
              <!-- 对话列表栏 -->
              <el-scrollbar tag="section" ref="menusScrollbar" class="full-height" :native="false">
                <el-main class="main">
                  <p v-show="loadStatus == 1" class="empty-data">页面未加载</p>
                  <p v-show="loadStatus == 2" class="empty-data">
                    <el-icon style="position:relative;top:2px" class="lumen-loading"><ele-Loading /></el-icon> 数据加载中...
                  </p>
                  <p v-show="loadStatus == 3 && talkNum == 0" class="empty-data">暂无客户消息</p>
                  <p v-show="loadStatus == 3 && talkNum > 0" class="main-menu">
                    <span class="title">消息记录 ({{ talkNum }})</span>
                  </p>
                  <!-- 对话列表 -->
                  <template v-if="loadStatus == 3">
                    <div
                      v-for="item in talkItems"
                      :key="item.index_name"
                      class="talk-item pointer"
                      :class="{ active: index_name == item.index_name }"
                      @click="clickTab(item.index_name)"
                      @contextmenu.prevent="talkItemsMenu(item, $event)"
                    >
                      <div class="avatar-box">
                          <span v-show="!item.avatar">
                            {{ (item.remark_name ? item.remark_name : item.name).substr(0, 1) }}
                          </span>
                          <el-image v-show="item.avatar" :src="item.avatar">
                            <template #error>
                              <el-image :src="detaultAvatar"></el-image>
                            </template>
                          </el-image>
                          <div v-show="item.is_top == 0" class="top-mask" @click.stop="topChatItem(item)">
                            <el-icon><ele-Top /></el-icon>
                          </div>
                      </div>
                      <div class="card-box">
                        <div class="title">
                          <div class="card-name">
                            <p class="nickname">{{ item.remark_name ? item.remark_name : item.name }}</p>
                            <div v-show="item.unread_num" class="larkc-tag">{{ item.unread_num }}条未读</div>
                            <div v-show="item.is_top" class="larkc-tag top">TOP</div>
                            <div v-show="item.is_robot" class="larkc-tag top">BOT</div>
                            <div v-show="item.talk_type == 2" class="larkc-tag group">群组</div>
                            <div v-show="item.is_disturb" class="larkc-tag disturb">
                              <el-icon><ele-MuteNotification /></el-icon>
                            </div>
                          </div>
                          <div class="card-time">
                            <Utime :value="item.updated_at"></Utime>
                          </div>
                        </div>
                        <div class="content">
                          <template v-if="index_name != item.index_name && item.draft_text">
                            <span class="draft-color">[草稿]</span>
                            <span>{{ item.draft_text }}</span>
                          </template>
                          <template v-else>
                            <template v-if="item.is_robot == 0">
                              <span v-if="page_status == 2 && item.talk_type == 1" :class="{ 'online-color': item.is_online == 1 }">
                                [{{ item.is_online == 1 ? '在线' : '离线' }}]
                              </span>
                              <span v-else-if="page_status == 3 && item.talk_type == 1" :class="{ 'online-color': item.is_online == 1 }">
                                [{{ item.is_online == 1 ? '正在聊' : '待接入' }}]
                              </span>
                              <!-- <span v-else>[群消息]</span> -->
                            </template>
                            <span>{{ item.msg_text }}</span>
                          </template>
                          <!-- && item.is_online != 1 -->
                          <el-button v-if="page_status == 3 && item.talk_type == 1" size="small" type="primary" plain @click.prevent.stop="connectCustomer(item)">接入</el-button>
                        </div>
                      </div>
                    </div>
                  </template>
                </el-main>
              </el-scrollbar>
            </el-container>
        </el-aside>

        <!-- 聊天面板容器 -->
        <el-main class="ov-hidden full-height no-padding panel-main">
          <el-empty v-if="index_name == null" description="暂无数据" />
          <TalkPanel
            v-else-if="status_btn"
            class="full-height"
            :params="params"
            :is-online="isFriendOnline"
            @change-talk="changeTalk"
            @close-talk="closeTalk"
          />
        </el-main>
      </el-container>
    </div>
  </div>
</template>

<script>
import { reactive, toRefs, ref, computed, nextTick } from 'vue'
import { Search } from '@element-plus/icons-vue'
import { useChatTalk } from '/@/stores/chat/talk'
import { useDialogueInfo } from '/@/stores/chat/dialogue'
import { findTalkIndex, getCacheIndexName } from '/@/views/chat/utils/talk.js'
import detaultAvatar from '/@/assets/detault-avatar.jpg'
import { useChatApi } from '/@/api/chat/index'
import Utime from '/@/views/chat/components/Utime.vue'
import { useRoute } from 'vue-router'
import ContextMenu from '@imengyu/vue3-context-menu'
import '@imengyu/vue3-context-menu/lib/vue3-context-menu.css'
import TalkPanel from '/@/views/chat/components/TalkPanel.vue'

export default {
  name: 'MessageShop',
  components: {
    Utime,
    TalkPanel
  },
  setup() {
    const menusScrollbar = ref()
    const chatTalk = useChatTalk()
    const dialogueInfo = useDialogueInfo()
    const chatApi = useChatApi()
    const route = useRoute()
    const state = reactive({
      input: '',
      params: { // 对话面板的传递参数
        talk_type: 0,
        receiver_id: 0,
        nickname: '',
        talk_source: 0
      },
      status_btn:false
    })
    const page_status = computed(() =>{
      return route.path == '/chat/message/shop' ? '2' : '3'
    })
    const topItems = computed(() => {
      return chatTalk.topItems.filter(item => (item.talk_source == page_status.value && item.talk_type != 2))
    })
    const loadStatus = computed(() => {
      return chatTalk.loadStatus
    })
    const talkNum = computed(() => {
      return chatTalk.talkItems.filter(item => (item.talk_source == page_status.value && item.talk_type != 2)).length
    })
    const index_name = computed(() => {
      return dialogueInfo.index_name
    })
    const talks = computed(() => {
      return chatTalk.items
    })
    const unreadNum = computed(() => {
      return chatTalk.unreadNum
    })
    const talkItems = computed(() => {
      // TO DO debug 测试 .filter(item => (item.talk_source == page_status.value && item.talk_type != 2))
      return chatTalk.talkItems
    })
    // 切换聊天栏目
    const clickTab = (index_name) => {
      let index = findTalkIndex(index_name)
      state.status_btn = false
      if (index == -1) return
      let item = talks.value[index]
      let [talk_type, receiver_id] = index_name.split('_')
      let nickname = item.remark_name ? item.remark_name : item.name
      // console.log(item)
      state.params = {
        talk_type,
        receiver_id,
        nickname,
        is_robot: item.is_robot,
        talk_source: item.talk_source
      }
      dialogueInfo.UPDATE_DIALOGUE_MESSAGE({
        talk_type,
        receiver_id,
        is_robot: item.is_robot
      })
      nextTick(() => {
        if (index_name == state.index_name) {
          chatTalk.UPDATE_TALK_ITEM({
            index_name,
            unread_num: 0
          })
          // 清空消息未读数(后期改成WebSocket发送消息)
          chatApi.ServeClearTalkUnreadNum({
            talk_type: parseInt(talk_type),
            receiver_id: parseInt(receiver_id)
          })
        }
        state.status_btn = true
      })
    }
    // 对话列表的右键自定义菜单
    const talkItemsMenu = (item, event) => {
          
      event.preventDefault()
    
      ContextMenu.showContextMenu({
        x: event.x,
        y: event.y,
        items: [
          { 
            label: "客户信息", 
            icon: 'fa-id-badge',
            iconFontClass: 'fa',
            disabled: item.talk_type == 2 || item.is_robot == 1,
            onClick: () => {
              state.user_id = item.receiver_id
              state.showUserDetail = true
            }
          },
          {
            label: '修改备注',
            icon: 'fa-pencil-square',
            iconFontClass: 'fa',
            disabled: item.talk_type == 2 || item.is_robot == 1,
            onClick: () => {
              editFriendRemarks(item)
            },
          },
          {
            label: item.is_top == 0 ? '会话置顶' : '取消置顶',
            icon: item.is_top == 0 ? 'fa-arrow-up' : 'fa-arrow-down',
            iconFontClass: 'fa',
            onClick: () => {
              topChatItem(item)
            },
          },
          // {
          //   label: item.is_disturb == 0 ? '消息免打扰' : '开启消息提示',
          //   icon:
          //     item.is_disturb == 0
          //       ? 'fa-bell-slash'
          //       : 'fa-bell',
          //   iconFontClass: 'fa',
          //   disabled: item.is_robot == 1,
          //   onClick: () => {
          //     setNotDisturb(item)
          //   },
          // },
          // {
          //   label: '移除会话',
          //   icon: 'fa-trash',
          //   iconFontClass: 'fa',
          //   onClick: () => {
          //     delChatItem(item)
          //   },
          // },
          // {
          //   label: item.talk_type == 1 ? '删除好友' : '退出群聊',
          //   icon: 'fa-user-times',
          //   iconFontClass: 'fa',
          //   disabled: item.is_robot == 1,
          //   onClick: () => {
          //     let title = item.talk_type == 1 ? '删除好友' : '退出群聊'
          //     ElMessageBox.confirm(
          //       `此操作将 <span style="color:red;font-size:16px;">${title}</span>, 是否继续?`,
          //       '提示',
          //       {
          //         confirmButtonText: '确定',
          //         cancelButtonText: '取消',
          //         type: 'warning',
          //         center: true,
          //         dangerouslyUseHTMLString: true,
          //       }
          //     ).then(() => {
          //       if (item.talk_type == 1) {
          //         removeFriend(item)
          //       } else {
          //         removeGroup(item)
          //       }
          //     })
          //   },
          // }
        ]
      })
    }
      
    // 置顶栏右键菜单栏
    const topItemsMenu = (item, event) => {
      event.preventDefault()
      ContextMenu.showContextMenu({
        x: event.x,
        y: event.y,
        items: [{
            label: item.is_top == 0 ? '会话置顶' : '取消置顶',
            icon: item.is_top == 0 ? 'fa-arrow-up' : 'fa-arrow-down',
            iconFontClass: 'fa',
            onClick: () => {
              topChatItem(item)
            }
        }]
      })
      return false
    }
    
    // 会话列表置顶
    const topChatItem = (item) => {
      chatApi.ServeTopTalkList({
        list_id: item.id,
        type: item.is_top == 0 ? 1 : 2,
      }).then(() => {
        chatTalk.UPDATE_TALK_ITEM({
          index_name: item.index_name,
          is_top: item.is_top == 0 ? 1 : 0
        })
      })
    }
    
    // 当前对话好友在线状态
    const isFriendOnline = computed(() => {
      let index = findTalkIndex(index_name.value)
      return index >= 0 && talks.value[index].is_online == 1
    })
    
    // 修改当前对话
    const changeTalk = (index_name) => {
      sessionStorage.setItem('send_message_index_name', index_name)
      chatTalk.LOAD_TALK_ITEMS()
    }
    
    // 关闭当前对话及刷新对话列表
    const closeTalk = () => {
      dialogueInfo.UPDATE_DIALOGUE_MESSAGE({
        talk_type: 0,
        receiver_id: 0,
        is_robot: 0
      })
      chatTalk.LOAD_TALK_ITEMS()
    }
    // 接入对话
    const connectCustomer = (item) => {
      // TO DO 接入对话
      console.log(item)
    }
    return {
      ...toRefs(state),
      Search,
      menusScrollbar,
      loadStatus,
      talkNum,
      index_name,
      talks,
      unreadNum,
      talkItems,
      clickTab,
      detaultAvatar,
      talkItemsMenu,
      topItemsMenu,
      topItems,
      isFriendOnline,
      changeTalk,
      closeTalk,
      page_status,
      connectCustomer
    }
  }
}
</script>

<style scoped lang="scss">
.page-container{
  padding: 0 !important;
  height: 100vh;
}
.panel-main{
  background: var(--next-color-white);
  overflow: hidden;
}
:deep(.el-scrollbar__wrap) {
  overflow-x: hidden;
}
:deep(.el-button i.el-icon){
   margin-right: 0;
}
.main-layout {
  height: 100%;
}
.aside-box {
  position: relative;
  border-right: 1px solid var(--el-border-color-light);
  overflow: hidden;
  padding: 0;
  transition: width 0.3s;
  background: var(--next-color-white);
  .header {
    display: flex;
    flex-direction: row;
    align-items: center;
    padding: 0 15px;
    .from-search {
      flex: 1 1;
      flex-shrink: 0;
    }
    .tools {
      flex-basis: 32px;
      flex-shrink: 0;
      height: 32px;
      margin-left: 15px;
      cursor: pointer;
      text-align: center;
      position: relative;
      user-select: none;
      .tools-menu {
        position: absolute;
        right: 0;
        top: 38px;
        width: 100px;
        min-height: 80px;
        box-sizing: border-box;
        background-color: rgba(31, 35, 41, 0.9);
        border-radius: 5px;
        z-index: 1;
        padding: 3px 0;
        .menu-item {
          height: 40px;
          line-height: 40px;
          color: white;
          font-size: 14px;
  
          &:hover {
            background-color: rgba(70, 72, 73, 0.9);
          }
        }
      }
    }
  }
  .subheader {
    display: flex;
    flex-direction: row;
    flex-wrap: wrap;
    padding: 5px 8px;
    overflow: hidden;
    flex-shrink: 0;
    justify-content: flex-start;
    background: aliceblue;
    .top-item {
      flex-basis: 41px;
      flex-shrink: 0;
      height: 50px;
      margin: 3px 0 3px 2px;
      display: flex;
      flex-direction: column;
      justify-content: space-between;
      align-items: center;
      cursor: pointer;
      .avatar {
        flex-basis: 32px;
        width: 32px;
        height: 32px;
        background-color: var(--el-color-primary);
        border-radius: 50%;
        display: flex;
        justify-content: center;
        align-items: center;
        font-size: 10px;
        color: white;
        flex-shrink: 0;
        overflow: hidden;
        user-select: none;
        img {
          width: 100%;
          height: 100%;
          background-color: white;
        }
      }
      .name {
        font-size: 12px;
        text-align: center;
        color: #8f959e;
        transform: scale(0.84);
        text-align: center;
        line-height: 20px;
        word-break: break-all;
        overflow: hidden;
        &.active {
          color: var(--el-color-primary);
        }
      }
    }
    &.shadow {
      box-shadow: 0 2px 6px 0 rgba(31, 35, 41, 0.05);
    }
  }
}
.aside-box .main {
  overflow: hidden;
  padding: 0;
  .empty-data {
    text-align: center;
    padding-top: 40px;
    color: #ccc;
  }
  .main-menu {
    display: flex;
    flex-direction: row;
    justify-content: space-between;
    padding: 6px 10px 6px 10px;
    align-items: center;
    user-select: none;
    .title {
      font-size: 12px;
      font-weight: 600;
      color: #1f2329;
    }
    .icon {
      cursor: pointer;
    }
  }
  .talk-item {
    padding: 8px 10px;
    height: 55px;
    display: flex;
    flex-direction: row;
    align-items: center;
    border-left: 3px solid transparent;
    transition: 0.2s ease-in;
    .avatar-box {
      height: 35px;
      width: 35px;
      flex-shrink: 0;
      background-color: var(--el-color-primary);
      border-radius: 50%;
      display: flex;
      justify-content: center;
      align-items: center;
      font-size: 14px;
      color: white;
      user-select: none;
      transition: ease 1s;
      position: relative;
      overflow: hidden;
      img {
        width: 100%;
        height: 100%;
        background-color: white;
        border-radius: 3px;
      }
      .top-mask {
        width: 100%;
        height: 100%;
        background-color: rgba(22, 25, 29, 0.6);
        position: absolute;
        top: 0;
        left: 0;
        color: white;
        display: none;
        align-items: center;
        justify-content: center;
        font-weight: bold;
      }
      &:hover .top-mask {
        display: flex;
      }
    }
    .card-box {
      height: 45px;
      display: flex;
      align-content: center;
      flex-direction: column;
      flex: 1 1;
      margin-left: 10px;
      overflow: hidden;
      .title {
        width: 100%;
        height: 20px;
        display: flex;
        align-items: center;
        .card-name {
          color: #1f2329;
          font-size: 14px;
          line-height: 20px;
          flex: 1 1;
          display: -webkit-flex;
          display: -ms-flexbox;
          display: flex;
          align-items: center;
          overflow: hidden;
          .nickname {
            font-weight: 400;
            white-space: nowrap;
            overflow: hidden;
            text-overflow: ellipsis;
            margin-right: 3px;
          }
          .top {
            color: #dc9b04 !important;
            background-color: #faf1d1 !important;
          }
          .group {
            color: #3370ff !important;
            background-color: #e1eaff !important;
            font-size: 13px;
          }
          .disturb {
            color: var(--el-text-color-regular) !important;
            background-color: transparent !important;
            padding: 0;
            i {
              font-size: 15px;
            }
          }
        }
      }
      .card-time {
        color: #8f959e;
        font-size: 12px;
        margin-left: 10px;
        user-select: none;
      }
      .content {
        font-size: 13px;
        line-height: 18px;
        color: #8f959e;
        margin-top: 3px;
        font-weight: 300;
        overflow: hidden;
        white-space: nowrap;
        text-overflow: ellipsis;
        display: flex;
        justify-content: space-between;
        align-items: center;
        span:first-child {
          margin-right: 5px;
        }
        .online-color {
          color: #4aa71c;
          font-weight: 300;
        }
        .draft-color {
          color: red;
          font-weight: 300;
        }
        :deep(.el-button){
          padding: 4px 10px;
          height: unset;
        }
      }
    }
    &:hover {
      background-color: #eff0f1;
    }
    &.active {
      .avatar-box {
        border-radius: 5px;
      }
      background-color: #eff0f1;
    }
  }
}
@media screen and (max-width: 800px) {
  .aside-box {
    width: 220px !important;
    .subheader {
      display: none;
    }
    .card-box .larkc-tag {
      display: none;
    }
  }
}
.larkc-tag {
  font-size: 12px;
  font-weight: 400;
  display: inline-flex;
  align-items: center;
  justify-content: center;
  padding: 0 6px;
  height: 20px;
  border-radius: 2px;
  cursor: default;
  user-select: none;
  background-color: #dee0e3;
  transform: scale(0.83);
  transform-origin: left;
  flex-shrink: 0;
}
</style>